package com.codeworker.app;

import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.NavigationUI;

import com.codeworker.app.data.common.Constant;
import com.codeworker.app.databinding.ActivityMainBinding;
import com.codeworker.app.ui.wrapper.MyApplication;
import com.codeworker.app.utils.UiUtils;

import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    private SharedPreferences spData;

    private boolean mIsActive = true;

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        spData = getSharedPreferences("SharedPreferences", MODE_PRIVATE);

        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
                .findFragmentById(R.id.nav_host_fragment_activity_main);
        NavController navController = Objects.requireNonNull(navHostFragment).getNavController();
        NavigationUI.setupWithNavController(binding.navView, navController);

        // 首次进入程序，如果开启密码保护，则需要密码验证
        if (MyApplication.activityLinkedList.size() == 1 &&
                spData.getString("settingPassword", Constant.CLOSE_FINGER_PROTECT)
                .equals(Constant.START_FINGER_PROTECT)) {
            mIsActive = true;
            UiUtils.doAuthentication(this);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (UiUtils.isAppOnBackground(this.getApplication())) {
            mIsActive = false;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onRestart() {
        super.onRestart();
        if (!mIsActive && spData.getString("settingPassword", Constant.CLOSE_FINGER_PROTECT)
                .equals(Constant.START_FINGER_PROTECT)) {
            mIsActive = true;
            UiUtils.doAuthentication(this);
        }
    }
}